import datetime
import json
import os
import shutil

import jwt
from django.http import HttpResponse, JsonResponse
from jwt import PyJWTError

from .crl import GetNamespace
from .models import Project, StarsPro, ProjectSerializer
from .crl import CpPodToLocal,localpath
from .views import CheckUserProject


def StarProject(request, id):
    body = json.loads(request.body)
    token = body["token"]
    try:
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse(status=401, content="请重新登录")
    project = Project.objects.filter(id=id)
    if len(project) == 0:
        return HttpResponse("项目不存在", status=202)
    project = project[0]
    stars = StarsPro.objects.filter(project=project, user_id=user["id"])
    if request.method == 'POST':
        if len(stars) == 0:
            star = StarsPro(project=project, user_id=user["id"])
            star.save()
            project.stars += 1
            project.save()
            return HttpResponse("OK")
        return HttpResponse("已收藏过", status=201)
    if request.method == 'DELETE':
        if len(stars) != 0:
            star = stars[0]
            star.delete()
            project.stars -= 1
            project.save()
            return HttpResponse("OK")
        return HttpResponse("未收藏", status=201)


def CloneTry(request):
    if request.method == 'GET':
        token = request.GET.get("token")
        id = request.GET.get("id")
        ## 验证
        try:
            user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
        except PyJWTError:
            return HttpResponse(status=401, content="请重新登录")
        project = Project.objects.filter(id=id)
        if len(project) == 0:
            return HttpResponse("项目不存在", status=202)
        project = project[0]

        ## 查找克隆项目是否已存在
        projects = Project.objects.filter(user_id=user["id"])
        for pro in projects:
            if pro.name == "fork from "+project.name:
                return HttpResponse(pro.id)

        return HttpResponse(0)


def CloneProject(request):
    body = json.loads(request.body)
    token = body["token"]
    try:
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse(status=401, content="请重新登录")
    project = Project.objects.filter(id=body["id"])
    if len(project) == 0:
        return HttpResponse("项目不存在", status=202)
    project = project[0]

    new_pro = Project(name="fork from "+project.name, introduction=project.introduction,
                      image_id=project.image_id, user_id=user["id"],edittime=datetime.datetime.now())
    new_pro.save()

    project.folks += 1
    project.save()

    CpPodToLocal(project.id)
    source_path = os.path.abspath('/root/data/%s/data' % project.id)
    target_path = os.path.abspath('/root/data/%s/data' % new_pro.id)

    if not os.path.exists(target_path):
        # 如果目标路径不存在原文件夹的话就创建
        os.makedirs(target_path)

    if os.path.exists(source_path):
        # 如果目标路径存在原文件夹的话就先删除
        shutil.rmtree(target_path)

    shutil.copytree(source_path, target_path)

    return JsonResponse(ProjectSerializer(new_pro))


def ChangePublic(request,id):
    res = CheckUserProject(request.GET.get("token"), id)
    if type(res) != Project:
        return res
    pro = res
    pro.ispublic = not pro.ispublic
    pro.save()
    return HttpResponse()


def ShowHtml(request,id):
    project = Project.objects.get(id=id)
    if not project.ispublic:
        res = CheckUserProject(request.GET.get("token"), id)
        if type(res) != Project:
            return res

    CpPodToLocal(id)
    path = localpath(id)

    if os.path.exists("/usr/local/nginx/html/data/"+ str(id)):
        shutil.rmtree("/usr/local/nginx/html/data/" + str(id))

    f = None
    if os.path.exists(path + 'readme.ipynb'):
        f = path + 'readme.ipynb'
    else :
        if os.path.exists(path):
            for filename in os.listdir(path):
                if filename.endswith(".ipynb"):
                    f = path + filename
                    break
    if f is None:
        return HttpResponse(status=203,content="无ipynb文件")
    targetpath = "/usr/local/nginx/html/data/" + str(id)
    if not os.path.exists(targetpath):
        os.makedirs(targetpath)
    cmd = "jupyter nbconvert --to html --output %s/index.html %s"%(targetpath,f)
    print(cmd)
    print(os.system(cmd))
    return HttpResponse()